package msg

//annotation:Message-service
//author:{"name":"Message","tel":"18928776452","email":"XUnion@GMail.com"}
import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"sevlteServer/auto"
	"sevlteServer/tool"
)

func Enroll(author string) {
	var developer *tool.ModuleAuthor
	if author != "" {
		var d tool.ModuleAuthor
		err := json.Unmarshal([]byte(author), &d)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		developer = &d
	}

	auto.AddService(&tool.ServeEndPoint{
		Fn: LoadMsg,

		Path: "/loadmsg",
		Name: "loadmsg",

		Developer: developer,
	})
}

func LoadMsg(r *http.Request, w http.ResponseWriter) {
	res, err := tool.DbPool.Query(context.Background(), "select id,message,from_user,to_user,creat_at from chat_log")
	if err != nil {
		fmt.Println(err.Error())
		tool.Resp(w, &tool.ReplyProto{Status: -200})
		return
	}
	type replyMsg struct {
		Status int            `json:"status"`
		Msgs   []tool.Message `json:"msgs"`
	}

	msgs := replyMsg{Status: 0}
	for res.Next() {
		var msg tool.Message

		err := res.Scan(&msg.Id, &msg.Msg, &msg.From, &msg.To, &msg.At)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		msgs.Msgs = append(msgs.Msgs, msg)
	}
	buf, err := json.Marshal(&msgs)
	if err != nil {
		fmt.Println(err.Error())
		tool.Resp(w, &tool.ReplyProto{Status: -200})
		return
	}
	_, err = w.Write(buf)
	if err != nil {
		fmt.Println(err.Error())
		tool.Resp(w, &tool.ReplyProto{Status: -200})
		return
	}
}
